﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace testProtobuf
{
    class SocketServer
    {
        private static int myPort = 8888;
        private static Socket serverSocket = null;
        public Thread myThread;
        private static byte[] result = new byte[83];

        public static Thread receivedThread;

        public void startServer()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myPort));
            serverSocket.Listen(10);
            Console.WriteLine("启动监听  " + serverSocket.LocalEndPoint.ToString() + " 成功......");
            myThread = new Thread(ListenClientConnect);
            myThread.Start();
        }


        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                receivedThread = new Thread(ReceiveMessage);
                receivedThread.Start(clientSocket);

            }
        }

        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = clientSocket as Socket;
            while (true)
            {
                try
                {
                    int receiveLength = myClientSocket.Receive(result);

                    Console.WriteLine("接收客户端  " + myClientSocket.RemoteEndPoint.ToString() + "消息 " + Encoding.UTF8.GetString(result, 0, receiveLength));


                    //Person person = Person.ParseFrom(result);

                    //Console.WriteLine("玩家姓名  " + person.Name);
                    //Console.WriteLine("玩家国籍  " + person.CountryInfo.Name);
                    //Console.WriteLine("玩家电话类型  " + person.GetPhone(0).ToString());

                }
                catch (System.Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    myClientSocket.Disconnect(true);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();

                    break;
                }
            }
        }

        public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }
    }
}
